package com.camus.utils;

import java.math.BigDecimal;
import java.util.Objects;

public class BigDecimalUtils {

	public static boolean isEqual(final BigDecimal l, final BigDecimal r) {
		if (l == r) {
			return true;
		}
		if (l == null || r == null) {
			return false;
		}
		return l.compareTo(r) == 0;
	}

	public static boolean isEqualWithinTolerance(final BigDecimal l, final BigDecimal r, final BigDecimal tolerance) {
		if (l == r) {
			return true;
		}
		if (l == null || r == null) {
			return false;
		}
		if (tolerance == null || BigDecimal.ZERO.compareTo(tolerance) == 0) {
			return isEqual(l, r);
		}
		BigDecimal upper = r.add(tolerance.abs());
		BigDecimal lower = r.subtract(tolerance.abs());
		return l.compareTo(upper) <= 0 && l.compareTo(lower) >= 0;
	}

	public static int isWithinRange(final BigDecimal src, final BigDecimal upper, final BigDecimal lower) {
		Objects.requireNonNull(src);
		Objects.requireNonNull(upper);
		Objects.requireNonNull(lower);
		if (src.compareTo(lower) < 0) {
			// 小于小值
			return -1;
		} else if (src.compareTo(upper) > 0) {
			// 大于大值
			return 1;
		}
		// 在范围内
		return 0;
	}

}
